/**
 * Dear programmer:
 * When I wrote this code, only god and I knew how it worked.
 * Now, only god knows it!
 *
 * @author: Pegasus  Date: 2018-12-15 Time: 23:16
 *
 * 取消清洁工单
 */

import React, {Component} from 'react';
import {
    SafeAreaView,
    View,
    Text,
    TouchableOpacity,
    TextInput, ToastAndroid,PermissionsAndroid
} from 'react-native';
import {connect} from 'react-redux';
import {styles} from './OrderFailedScreen.Style';
import {
    COLOR_FOCUS,
    COLOR_LINK,
    COLOR_WHITE,
    FONT_COLOR_SUB_TITLE,
    FONT_SIZE_TITLE
} from "../../../../constant/PHColors"
import {cancelSweepOrder} from "./Actions"
import {FetchStatus} from "../../../../configuration/RequestConfiguration";
import {ReturnStatus} from "../../../../configuration/ReturnStatus";
import {doDisplaySuccessMessage, doDisplayWarnMessage} from "../../../../component/Message/Action";
import PropTypes from "prop-types";
import {changeOrderStatus, changeSweepOrderStatus} from "../../../../component/BottomButtonView/Actions";
import Sound from 'react-native-sound';                        // 播放声音组件
import {AudioRecorder, AudioUtils} from 'react-native-audio';
import {SCREEN_WIDTH} from "../../../../constant/PHScreen";
import {AppRequestPath} from "../../../../configuration/AppConfig";
import {getStore} from "../../../../configuration/StoreConfiguration";
import User from "../../../../model/User/User";
import {API_UPLOADIMG_AUDIO} from "../../../../constant/API";

class OrderFailedScreen extends Component {

    static navigationOptions = ({navigation}) => ({
        title: '不通过检查原因',
    });

    //构造
    constructor(props) {
        super(props);
        this.state = {
            remark:'',
            active:'',
            orderid:this.props.navigation.getParam("orderid"),

            hasPermission: undefined, //授权状态
            audioPath: AudioUtils.DocumentDirectoryPath + '/test.aac', // 文件路径
            recording: false, //是否录音
            pause: false, //录音是否暂停
            stop: false, //录音是否停止
            currentTime: 0, //录音时长
            audioBase64:'',     //base64格式的音频文件
            soundState_c:'点击播放',
        }
    }

    componentWillReceiveProps(nextProps, nextContext): void {
        let {dispatch} = this.props;

        if (nextProps.onChangeSweepOrderStatus !== this.props.onChangeSweepOrderStatus && nextProps.onChangeSweepOrderStatus.fetchStatus === FetchStatus.Success) {
            if (nextProps.onChangeSweepOrderStatus.RETURN === ReturnStatus.Success) {
                // ToastAndroid.show(nextProps.onChangeSweepOrderStatus.MSG, 1000);//提示
                doDisplaySuccessMessage(nextProps.onChangeSweepOrderStatus.MSG);
                this.props.navigation.navigate(this.props.navigation.getParam("page"));
                this.props.navigation.state.params.goBack();
            } else {
                dispatch(doDisplayWarnMessage(nextProps.onChangeSweepOrderStatus.MSG))
            }
        }
    }

    componentDidMount() {
        // 请求授权
        AudioRecorder.requestAuthorization()
            .then(isAuthor => {
                console.log('是否授权: ' + isAuthor)
                if(!isAuthor) {
                    return alert('请前往设置开启录音权限')
                }
                this.setState({hasPermission: isAuthor})
                this.prepareRecordingPath(this.state.audioPath);
                // 录音进展
                AudioRecorder.onProgress = (data) => {
                    this.setState({currentTime: Math.floor(data.currentTime)});
                };
                // 完成录音
                AudioRecorder.onFinished = (data) => {
                    // data 返回需要上传到后台的录音数据
                    console.log(this.state.currentTime)
                    console.log(data);
                    this.state.audioBase64 = data['base64']?data['base64']:'';
                };
            })
    };

    /**
     * AudioRecorder.prepareRecordingAtPath(path,option)
     * 录制路径
     * path 路径
     * option 参数
     */
    prepareRecordingPath = (path) => {
        const option = {
            SampleRate: 44100.0, //采样率
            Channels: 2, //通道
            AudioQuality: 'High', //音质
            AudioEncoding: 'aac', //音频编码
            OutputFormat: 'mpeg_4', //输出格式
            MeteringEnabled: false, //是否计量
            MeasurementMode: false, //测量模式
            AudioEncodingBitRate: 32000, //音频编码比特率
            IncludeBase64: true, //是否是base64格式
            AudioSource: 0, //音频源
        }
        AudioRecorder.prepareRecordingAtPath(path,option)
    }

    // 开始录音
    _record = async () => {
        if(!this.state.hasPermission) {
            return alert('没有授权')
        }
        if(this.state.recording) {
            return alert('正在录音中...')
        }
        if(this.state.stop) {
            this.prepareRecordingPath(this.state.audioPath)
        }
        this.setState({recording: true,pause: false})

        try {
            await AudioRecorder.startRecording()
        } catch (err) {
            console.log(err)
        }
    }

    // 暂停录音
    _pause = async () => {
        if(!this.state.recording) {
            return alert('当前未录音')
        }

        try {
            await AudioRecorder.pauseRecording()
            this.setState({pause: true, recording: false})
        } catch (err) {
            console.log(err)
        }
    }

    // 恢复录音
    _resume = async () => {
        if(!this.state.pause) {
            return alert('录音未暂停')
        }

        try {
            await AudioRecorder.resumeRecording();
            this.setState({pause: false, recording: true})
        } catch (err) {
            console.log(err)
        }
    }

    // 停止录音
    _stop = async () => {
        this.setState({stop: true, recording: false, paused: false});
        try {
            await AudioRecorder.stopRecording();
        } catch (error) {
            console.error(error);
        }
    }

    // 播放录音
    _play = async () => {
        let whoosh = new Sound(this.state.audioPath, '', (err) => {
            this.setState({soundState_c:"正在播放..."})
            if(err) {
                this.setState({soundState_c:"播放失败"})
                return console.log(err)
            }
            whoosh.play(success => {
                if(success) {
                    this.setState({soundState_c:"点击播放"})
                    console.log('success - 播放成功')
                }else {
                    this.setState({soundState_c:"播放失败"})
                    console.log('fail - 播放失败')
                }
            })
        })
    }


    render(){

        let { stop, recording, pause, currentTime } = this.state;

        return (
            <SafeAreaView style={styles.body}>
                <View style={styles.bodyTitle}>
                    <Text style={styles.bodyTitleText}>
                        请选择原因：
                    </Text>
                </View>
                {/* 填写原因 */}
                <View style={styles.bodyContainer}>
                    <View style={styles.radioBox}>
                        <TouchableOpacity activeOpacity={0.8} onPress={() => {
                            let active = '有人在住没法清洁';
                            if(this.state.active==='有人在住没法清洁'){
                                active = ''
                            }
                            this.setState({
                                active:active,
                            })
                        }}>
                            <View style={styles[(this.state.active==='有人在住没法清洁')?'radioButtonActive':'radioButton']} >
                                <Text style={{fontSize: FONT_SIZE_TITLE,color:(this.state.active==='有人在住没法清洁')?'#fff':'#969696'}}>
                                    有人在住没法清洁
                                </Text>
                            </View>
                        </TouchableOpacity>
                        <TouchableOpacity activeOpacity={0.8} onPress={() => {
                            let active = '分配错了房间';
                            if(this.state.active==='分配错了房间'){
                                active = ''
                            }
                            this.setState({
                                active:active,
                            })
                        }}>
                            <View style={styles[(this.state.active==='分配错了房间')?'radioButtonActive':'radioButton']}>
                                <Text style={{fontSize: FONT_SIZE_TITLE,color:(this.state.active==='分配错了房间')?'#fff':'#969696' }}>
                                    分配错了房间
                                </Text>
                            </View>
                        </TouchableOpacity>
                        <TouchableOpacity activeOpacity={0.8} onPress={() => {
                            let active = '房间没人住过';
                            if(this.state.active==='房间没人住过'){
                                active = ''
                            }
                            this.setState({
                                active:active,
                            })
                        }}>
                            <View style={styles[(this.state.active==='房间没人住过')?'radioButtonActive':'radioButton']}>
                                <Text style={{fontSize: FONT_SIZE_TITLE,color:(this.state.active==='房间没人住过')?'#fff':'#969696'}}>
                                    房间没人住过
                                </Text>
                            </View>
                        </TouchableOpacity>
                        <TouchableOpacity activeOpacity={0.8} onPress={() => {
                            let active = '工程问题无法清洁';
                            if(this.state.active==='工程问题无法清洁'){
                                active = ''
                            }
                            this.setState({
                                active:active,
                            })
                        }}>
                            <View style={styles[(this.state.active==='工程问题无法清洁')?'radioButtonActive':'radioButton']}>
                                <Text style={{fontSize: FONT_SIZE_TITLE,color:(this.state.active==='工程问题无法清洁')?'#fff':'#969696'}}>
                                    工程问题无法清洁
                                </Text>
                            </View>
                        </TouchableOpacity>
                    </View>
                    <View style={styles.inputBox}>
                        <TextInput
                            multiline={true}
                            maxLength={50}
                            style={{
                                fontSize: 20,
                                padding: 0,
                                height:100,
                                textAlignVertical: "top",
                            }}
                            placeholder='可输入其他原因'
                            keyboardType={'default'}
                            autoFocus={false}
                            underlineColorAndroid={'transparent'}
                            onChangeText={text => {
                                if(text.length>50){
                                    text = text.substring(0,50)
                                }
                                this.setState({
                                    remark:text,
                                })
                            }}
                        />
                        <View style={styles.textInputRight}>
                            <Text style={{fontSize: FONT_SIZE_TITLE, color: FONT_COLOR_SUB_TITLE}}>
                                {this.state.remark.length}
                                <Text style={{fontSize: FONT_SIZE_TITLE, color: FONT_COLOR_SUB_TITLE}}>
                                    /50
                                </Text>
                            </Text>
                        </View>
                    </View>
                    {/*<View style={styles.container}>
                        <Text style={styles.text} onPress={this._record}> Record(开始录音) </Text>
                        <Text style={styles.text} onPress={this._pause}> Pause(暂停录音) </Text>
                        <Text style={styles.text} onPress={this._resume}> Resume(恢复录音) </Text>
                        <Text style={styles.text} onPress={this._stop}> Stop(停止录音) </Text>
                        <Text style={styles.text} onPress={this._play}> Play(播放录音) </Text>
                        <Text style={styles.text}>
                            {
                                recording ? '正在录音' :
                                    pause ? '已暂停' : '未开始'
                            }
                        </Text>
                        <Text style={styles.text}>时长: {currentTime}</Text>
                    </View>*/}
                    <View style={styles.bottomButtonBox}>
                        {
                            stop ? (
                                <View style={{ flexDirection: 'row',justifyContent: 'space-between',margin: 0,width:SCREEN_WIDTH-30,}}>
                                    <TouchableOpacity activeOpacity={0.8} onPress={this._play}>
                                        <View style={{borderRadius: 3,
                                            backgroundColor:COLOR_LINK,
                                            color:'#fff',
                                            height: 40,
                                            width: (SCREEN_WIDTH-45)/2,
                                            marginBottom: 20,
                                            alignItems:'center',
                                            justifyContent: 'center',
                                            fontSize: FONT_SIZE_TITLE,
                                        }}>
                                            <Text style={{fontSize: 20, color: '#fff'}}>
                                                {this.state.soundState_c}
                                            </Text>
                                        </View>
                                    </TouchableOpacity>
                                    <TouchableOpacity activeOpacity={0.8} onPress={() => {
                                        this.prepareRecordingPath(this.state.audioPath);
                                        this.setState({stop: false, recording: false, paused: false,currentTime:0});
                                    }}>
                                        <View style={{borderRadius: 3,
                                            backgroundColor:'#999999',
                                            color:'#fff',
                                            height: 40,
                                            width: (SCREEN_WIDTH-45)/2,
                                            marginBottom: 20,
                                            alignItems:'center',
                                            justifyContent: 'center',
                                            fontSize: FONT_SIZE_TITLE,
                                        }}>
                                            <Text style={{fontSize: 20, color: '#fff'}}>
                                                删除录音
                                            </Text>
                                        </View>
                                    </TouchableOpacity>
                                </View>
                            ): (
                                <TouchableOpacity activeOpacity={0.8} onPressIn={this._record} onPressOut={this._stop}>
                                    <View style={styles.recordButton}>
                                        <Text style={{ color: '#FFF'}}>
                                            {
                                                recording ? '正在录音 时长'+currentTime+'S' :
                                                    pause ? '已暂停' : '按住说话'
                                            }
                                        </Text>
                                    </View>
                                </TouchableOpacity>
                            )
                        }

                    </View>
                    <View style={styles.bottomButtonBox}>
                        <TouchableOpacity activeOpacity={0.8} onPress={() => {
                            this._submitClick()
                        }}>
                            <View style={styles.bottomButton}>
                                <Text style={{fontSize: 20, color: '#fff'}}>
                                    确定
                                </Text>
                            </View>
                        </TouchableOpacity>
                        <TouchableOpacity activeOpacity={0.8} onPress={() => {
                            this.props.navigation.navigate(this.props.navigation.getParam("page"));
                        }}>
                            <View style={styles.bottomButton}>
                                <Text style={{fontSize: 20, color: '#fff'}}>
                                    取消
                                </Text>
                            </View>
                        </TouchableOpacity>
                    </View>
                </View>
            </SafeAreaView>
        )
    }

    _submitClick=()=>{
        let {dispatch} = this.props;
        let remark = this.state.active+this.state.remark;

        if(this.state.audioBase64!==''){
            let token = getStore().getState().onToken;
            User.getUser(user => {
                let data = new FormData();
                data.append('base64', this.state.audioBase64);
                data.append("token", token);
                data.append("prefix", "orderRemarkAudio");
                data.append("orderid", this.state.orderid);
                data.append("hotelId", user.hotelId);
                console.log(JSON.stringify(data))
                try {
                    fetch(AppRequestPath()+ API_UPLOADIMG_AUDIO, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'multipart/form-data;charset=utf-8'
                        },
                        body: data
                    }).then(function(response) {
                        return response.json();
                    }).then(data=>{
                        console.log(JSON.stringify(data))

                        let str = {"whsk_Order_Sweep_event":{"orderid":this.state.orderid,"remark":remark,"sound":data.DATA[0].filename},"whsk_Order_event":{"operation":'不通过检查'}}
                        dispatch(changeSweepOrderStatus(JSON.stringify(str)));
                        // imageArr[i]['path']=data["url"];
                        // if(imageArr[i]['localImg'])
                        //     delete imageArr[i]['localImg']
                        // if(lastIndex==i){
                        //     ToastAndroid.show('上传成功', 1000);
                        //     // this.props.navigation.goBack(imageArr);
                        //     this.props.navigation.state.params.goBack(imageArr);
                        // }
                    })
                } catch (err) {
                    console.log(err)
                }
            })

        }else{
            let str = {"whsk_Order_Sweep_event":{"orderid":this.state.orderid,"remark":remark},"whsk_Order_event":{"operation":'不通过检查'}}
            dispatch(changeSweepOrderStatus(JSON.stringify(str)));
        }


    }

}

const props = state => {
    return {
        onChangeSweepOrderStatus:state.onChangeSweepOrderStatus

    }
};

export default OrderFailedScreen = connect(props)(OrderFailedScreen);
